package com.xyzq.simpson.apm.web.controller;

import com.xyzq.simpson.apm.web.entity.InstanceEntity;
import com.xyzq.simpson.apm.web.entity.ServiceEntity;
import com.xyzq.simpson.apm.web.utils.DurationUtil;
import com.xyzq.simpson.apm.web.utils.ResponseEntity;
import com.xyzq.simpson.hibbert.service.api.ApplicationReportService;
import com.xyzq.simpson.hibbert.storage.es.dao.IMetadataQueryDAO;
import com.xyzq.simpson.hibbert.storage.es.manager.EsQueryManager;
import com.xyzq.simpson.lisa.spring.LisaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/apm/api/service")
public class ServiceController {
    protected Logger logger = LoggerFactory.getLogger(ServiceController.class);

    @RequestMapping(value = "/projectList", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity projectList(@RequestBody Map<String, Object> json) throws Exception {
        IMetadataQueryDAO metadataQueryDAO = EsQueryManager.instance().getService(IMetadataQueryDAO.class);
        long startTimeStamp = DurationUtil.getStartTimeStamp(json);
        List<String> allServices = metadataQueryDAO.getAllServices(startTimeStamp, 0L);
        Collections.sort(allServices, String.CASE_INSENSITIVE_ORDER);
        List<ServiceEntity> res = new ArrayList<>();
        for(int i = 0; i < allServices.size(); i++) {
            res.add(new ServiceEntity(allServices.get(i), i+1));
        }
        return new ResponseEntity().success(res);
    }

    @RequestMapping(value = "/ipList", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity ipList(@RequestBody Map<String, Object> json) throws Exception {
        IMetadataQueryDAO metadataQueryDAO = EsQueryManager.instance().getService(IMetadataQueryDAO.class);
        String projectName = String.valueOf(json.get("serviceId"));
        long startTimeStamp = DurationUtil.getStartTimeStamp(json);
        List<String> ips = metadataQueryDAO.getInstances(projectName, startTimeStamp, 0L);
        Collections.sort(ips, String.CASE_INSENSITIVE_ORDER);
        List<InstanceEntity> res = new ArrayList<>();
        res.add(new InstanceEntity("ALL", 1));
        for(int i = 0; i<ips.size(); i++) {
            res.add(new InstanceEntity(ips.get(i), i+2));
        }
        return new ResponseEntity().success(res);
    }

    @RequestMapping(value = "/index")
    @ResponseBody
    public String index() throws Exception {
        return "success";
    }


}